<?php

class ClassVenueController extends GxController {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('getAllCountry', 'getLocality', 'dynamicState', 'dynamicCity', 'getBatchDetails', 'getcourseBatchDetails', 'SelectedVenue'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('Classvenue', 'Coursevenue', 'getLocality', 'getAllVenue'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionClassvenue() {
        $model = new ClassVenue;
        $modelClassBatch = new ClassBatch;
        $authKey = Yii::app()->user->getState('authKey');
        //echo $authKey;die;
        if (!empty($authKey)) {

            $classes = Classes::model()->findByAttributes(array('auth_key' => $authKey));
            $userId = getLoginUserId();
            $selectedVenue = '';
            $classinfo = '';
            if (!empty($classes) && ($userId == $classes->users_id)) {
                /* find all venue details per class */
                $venuesWithClass = ClassWithVenue::model()->findAllByAttributes(array('classes_id' => $classes->id));
                if (isset($_POST['ClassVenue']['name'])) {
                    $this->saveClassVenueAddress($classes->id);
                    self::saveClassTicketBooked($classes->id);
                    self::saveOtherInfo($classes->id);
                    $this->redirect(array('ClassImage/classimages/'));
                }
                /* This is for all selected Venues With Class */
                if (!empty($venuesWithClass)) {
                    for ($i = 0; $i < count($venuesWithClass); $i++) {
                        $selectedVenue.= $venuesWithClass[$i]->class_venue_id . ',';
                    }
                    $selectedVenue = trim($selectedVenue, ",");
                }
                $classinfo = Classes::classOtherInformation($classes->id);

                $this->render('_classForm', array('model' => $model, 'modelClassBatch' => $modelClassBatch, 'venuesWithClass' => $venuesWithClass,
                    'classinfo' => $classinfo, 'selectedVenue' => $selectedVenue, 'classId' => $classes->id, 'authKey' => $authKey));
            }
        } else {
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
        }
    }

    public function actionCoursevenue() {
        $model = new ClassVenue;
        $modelCourseBatch = new CourseBatche;
        $authKey = Yii::app()->user->getState('authKey');
        if (!empty($authKey)) {
            $courses = Courses::model()->findByAttributes(array('auth_key' => $authKey));
            $userId = getLoginUserId();
            $selectedVenue = '';
            $courseinfo = '';
            if (!empty($courses) && ($userId == $courses->users_id)) {
                /* find all venue details per class */
                $venuesWithCourse = CourseWithVenue::model()->findAllByAttributes(array('courses_id' => $courses->id));
                if (isset($_POST['ClassVenue']['name'])) {                  
                    $this->saveCourseVenueAddress($courses->id);
                    $this->saveCourseTicketBooked($courses->id);
                    self::saveCourseOtherInfo($courses->id);
                    $this->redirect(array('ClassImage/courseimage/'));
                }
                /* This is for all selected Venues With Class */
                if (!empty($venuesWithCourse)) {
                    for ($i = 0; $i < count($venuesWithCourse); $i++) {
                        $selectedVenue.= $venuesWithCourse[$i]->course_venue_id . ',';
                    }
                    $selectedVenue = trim($selectedVenue, ",");
                }
                $courseinfo = Courses::courseOtherInformation($courses->id);

                $this->render('_courseVenue', array('model' => $model, 'modelCourseBatch' => $modelCourseBatch, 'venuesWithCourse' => $venuesWithCourse,
                    'courseinfo' => $courseinfo, 'selectedVenue' => $selectedVenue, 'courseId' => $courses->id, 'authKey' => $authKey));
            }
        } else {
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
        }
    }

    protected function saveClassVenueAddress($classId) {
        $venuesWithClass = ClassWithVenue::model()->findByAttributes(array('classes_id' => $classId));
        if (!empty($venuesWithClass)) {
            /* this code user for send a msg for when update class and venue and batch  start */
            $getVenues = classes::getclassWithVenues($classId);
            foreach ($getVenues as $value) {
                $BeforeUpdateclassWithVenue[] = $value['class_venue_id'];
                $BeforeUpdateclassBatchs = classes::getClassBatch($classId, $value['class_venue_id']);
                foreach ($BeforeUpdateclassBatchs as $value) {
                    $BeforeUpdateBatchStartDate[] = $value['start_date'];
                    $BeforeUpdateBatchStartTime[] = $value['start_time'];
                    $BeforeUpdateBatchEndTime[] = $value['end_time'];
                    $BeforeUpdateBatchPrice[] = $value['price'];
                    $BeforeUpdateBatchSeats[] = $value['seats'];
                    /*     this code for when need send a msg all usertypes               
                     *  $classEarlyDiscount = classes::getClassBatchEarlyBirdDiscount($classId, $value['id']);
                      $classGroupDiscount = classes::getClassBatchGroupDscount($classId, $value['id']);
                      foreach ($classEarlyDiscount as $earlykey => $earlyvalue) {
                      $BeforeUpdateclassVenueBatchEarlyDiscount[$earlykey][] = $earlyvalue;
                      }
                      foreach ($classGroupDiscount as $groupdiscountkey => $groupdiscountvalue) {
                      $BeforeUpdateclassVenueBatchGroupDiscount[$groupdiscountkey][] = $groupdiscountvalue;
                      } */
                }
            }
            /* ---------end------------------------------- */
            Classes::deleteClassesBatcheEarlyDiscount($classId);
            Classes::deleteClassesBatcheGroupDiscount($classId);
            Classes::deleteclassbatchweelymonthly($classId);
            Classes::deleteClassesBatcheSessions($classId);
            Classes::deleteClassesWithVenue($classId);
            Classes::deleteClassesStructure($classId);
            Classes::deleteClassesBatches($classId);

            
        }

        /**         * *********** save venue **************** */
        if (isset($_POST['ClassVenue']['name'])) {
            for ($venukey = 0; $venukey < count($_POST['ClassVenue']['name']); $venukey++) {
                /*                 * ************ save class with venue **************** */
                if (isset($_POST['ClassVenue']['venueId'][$venukey]) && !empty($_POST['ClassVenue']['venueId'][$venukey])) {
                    $classWithVenue = new ClassWithVenue;
                    $classWithVenue->setAttribute('classes_id', $classId);
                    $classWithVenue->setAttribute('class_venue_id', $_POST['ClassVenue']['venueId'][$venukey]);
                    $classWithVenue->save(false);
                    $venueId = $_POST['ClassVenue']['venueId'][$venukey];
                } else {
                    $modelClassVenue = new ClassVenue;
                    $modelClassVenue->setAttribute('name', $_POST['ClassVenue']['name'][$venukey]);
                    $modelClassVenue->setAttribute('address_line1', $_POST['ClassVenue']['address_line1'][$venukey]);
                    $modelClassVenue->setAttribute('address_line2', $_POST['ClassVenue']['address_line2'][$venukey]);
                    $modelClassVenue->setAttribute('venue_locality', $_POST['ClassVenue']['venue_locality'][$venukey]);
                    $modelClassVenue->setAttribute('zip_code', $_POST['ClassVenue']['zip_code'][$venukey]);
                    $modelClassVenue->setAttribute('country_id', $_POST['ClassVenue']['country_id'][$venukey]);
                    $modelClassVenue->setAttribute('state_id', $_POST['ClassVenue']['state_id'][$venukey]);
                    $modelClassVenue->setAttribute('city_id', $_POST['ClassVenue']['city_id'][$venukey]);
                    $modelClassVenue->setAttribute('users_id', getLoginUserId());
                    $modelClassVenue->setAttribute('status', SkillConfig::STATUS_ACTIVE);
                    $modelClassVenue->setAttribute('create_time', SkillConfig::CreateDateTime());
                    $modelClassVenue->save(false);
                    ClassWithVenue::saveLocality($_POST['ClassVenue']['venue_locality'][$venukey]);
                    $classWithVenue = new ClassWithVenue;
                    $classWithVenue->setAttribute('classes_id', $classId);
                    $classWithVenue->setAttribute('class_venue_id', $modelClassVenue->id);
                    $classWithVenue->save(false);
                    $venueId = $modelClassVenue->id;
                }
                $venueIndex = $_POST['venueIndex'][$venukey];
                /* condtion for update venue send a mail to user ad notification */
                if (!empty($venuesWithClass)) {
                    if (!in_array($venueId, $BeforeUpdateclassWithVenue)) {
                        $updateInformationClass[] = "Venue";
                    }
                }
                /* -----------end ----------------- */

                /**                 * *********** save batches according to venue **************** */
                if (isset($_POST['batchIndex'][$venueIndex])) {
                    for ($batchKey = 0; $batchKey < count($_POST['batchIndex'][$venueIndex]); $batchKey++) {
                        if (isset($_POST['ClassBatch']['ClassVenue'][$venueIndex]['seats'][$batchKey])) {
                            $modelClassBatch = new ClassBatch;
                            $modelClassBatch->setAttribute('start_date', $_POST['ClassBatch']['ClassVenue'][$venueIndex]['start_date'][$batchKey]);
                            $modelClassBatch->setAttribute('start_time', $_POST['ClassBatch']['ClassVenue'][$venueIndex]['start_time'][$batchKey]);
                            $modelClassBatch->setAttribute('end_time', $_POST['ClassBatch']['ClassVenue'][$venueIndex]['end_time'][$batchKey]);
                            $modelClassBatch->setAttribute('price', $_POST['ClassBatch']['ClassVenue'][$venueIndex]['price'][$batchKey]);
                            $modelClassBatch->setAttribute('seats', $_POST['ClassBatch']['ClassVenue'][$venueIndex]['seats'][$batchKey]);
                            $modelClassBatch->setAttribute('schedule_id', $_POST['ClassBatch']['ClassVenue'][$venueIndex]['schedule_id'][$batchKey]);
                            $modelClassBatch->setAttribute('classes_id', $classId);
                            $modelClassBatch->setAttribute('class_venue_id', $venueId);
                            $modelClassBatch->save(false);
                            $batchIndex = $_POST['batchIndex'][$venueIndex][$batchKey];
                            /* condtion for update batch send a mail to user ad notification */
                            if (!empty($venuesWithClass)) {
                                if ((!in_array($_POST['ClassBatch']['ClassVenue'][$venueIndex]['start_date'][$batchKey], $BeforeUpdateBatchStartDate)) || (!in_array($_POST['ClassBatch']['ClassVenue'][$venueIndex]['start_time'][$batchKey], $BeforeUpdateBatchStartTime)) || (!in_array($_POST['ClassBatch']['ClassVenue'][$venueIndex]['end_time'][$batchKey], $BeforeUpdateBatchEndTime)) || (!in_array($_POST['ClassBatch']['ClassVenue'][$venueIndex]['price'][$batchKey], $BeforeUpdateBatchPrice)) || (!in_array($_POST['ClassBatch']['ClassVenue'][$venueIndex]['seats'][$batchKey], $BeforeUpdateBatchSeats))) {
                                    $updateInformationClass[] = "Batch";
                                     Classes::model()->updateByPk($classId, array('class_exp' => SkillConfig::STATUS_DEACTIVE));
                                }
                            }
                            /* -----------end ----------------- */
                            /*                             * **************************  save batches early discount **************** */
                            if (isset($_POST['ClassEarlyDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['valid_to'])) {
                                for ($k = 0; $k < count($_POST['ClassEarlyDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['valid_to']); $k++) {
                                    if ($_POST['ClassEarlyDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['valid_to'][$k] <> ""):
                                        $modelClassEarlyDiscount = new ClassEarlyDiscount;
                                        $modelClassEarlyDiscount->setAttribute('discount_price', $_POST['ClassEarlyDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['discount_price'][$k]);
                                        $modelClassEarlyDiscount->setAttribute('in_percentage', $_POST['ClassEarlyDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['in_percentage'][$k]);
                                        $modelClassEarlyDiscount->setAttribute('valid_to', $_POST['ClassEarlyDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['valid_to'][$k]);
                                        $modelClassEarlyDiscount->setAttribute('status', SkillConfig::STATUS_ACTIVE);
                                        $modelClassEarlyDiscount->setAttribute('create_time', SkillConfig::CreateDateTime());
                                        $modelClassEarlyDiscount->setAttribute('class_batch_id', $modelClassBatch->id);
                                        $modelClassEarlyDiscount->setAttribute('classes_id', $classId);
                                        $modelClassEarlyDiscount->save(false);
                                    endif;
                                }
                            }

                            /**                             * *********** save batches group discount **************** */
                            if (isset($_POST['GroupDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['group_size'])) {
                                for ($k = 0; $k < count($_POST['GroupDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['group_size']); $k++) {
                                    if ($_POST['GroupDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['group_size'][$k] <> ""):
                                        $modelGroupDiscount = new GroupDiscount;
                                        $modelGroupDiscount->setAttribute('discount_amount', $_POST['GroupDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['discount_amount'][$k]);
                                        $modelGroupDiscount->setAttribute('discount_in_percentage', $_POST['GroupDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['discount_in_percentage'][$k]);
                                        $modelGroupDiscount->setAttribute('group_size', $_POST['GroupDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['group_size'][$k]);
                                        $modelGroupDiscount->setAttribute('status', SkillConfig::STATUS_ACTIVE);
                                        $modelGroupDiscount->setAttribute('create_time', SkillConfig::CreateDateTime());
                                        $modelGroupDiscount->setAttribute('class_batch_id', $modelClassBatch->id);
                                        $modelGroupDiscount->setAttribute('classes_id', $classId);
                                        $modelGroupDiscount->save(false);
                                    endif;
                                }
                            }

                            /*                             * ************ save batches schedule Session **************** */

                            if (isset($_POST['ClassScheduleSession']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['date'])) {
                                for ($k = 0; $k < count($_POST['ClassScheduleSession']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['date']); $k++) {
                                    if ($_POST['ClassScheduleSession']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['date'][$k] <> ""):
                                        $modelBatcheSession = new BatcheSession;
                                        $modelBatcheSession->setAttribute('date', $_POST['ClassScheduleSession']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['date'][$k]);
                                        $modelBatcheSession->setAttribute('start_time', $_POST['ClassScheduleSession']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['start_time'][$k]);
                                        $modelBatcheSession->setAttribute('end_time', $_POST['ClassScheduleSession']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['end_time'][$k]);
                                        $modelBatcheSession->setAttribute('batche_id', $modelClassBatch->id);
                                        $modelBatcheSession->setAttribute('classes_id', $classId);
                                        $modelBatcheSession->save(false);
                                    endif;
                                }
                            }
                            if (isset($_POST['ClassStructures']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['start_time'])) {
                                for ($k = 0; $k < count($_POST['ClassStructures']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['start_time']); $k++) {
                                    if ($_POST['ClassStructures']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['start_time'][$k] <> "" && $_POST['ClassStructures']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['end_time'][$k] <> "" && $_POST['ClassStructures']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['description'][$k] <> ""):
                                        $modelClassStructure = new ClassStructures;
                                        $modelClassStructure->setAttribute('start_time', $_POST['ClassStructures']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['start_time'][$k]);
                                        $modelClassStructure->setAttribute('end_time', $_POST['ClassStructures']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['end_time'][$k]);
                                        $modelClassStructure->setAttribute('description', $_POST['ClassStructures']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['description'][$k]);
                                        $modelClassStructure->setAttribute('class_batch_id', $modelClassBatch->id);
                                        $modelClassStructure->setAttribute('classes_id', $classId);
                                        $modelClassStructure->save(FALSE);
                                    endif;
                                }
                            }
                        }
                    }
                }
            }
        }
        if (!empty($updateInformationClass)) {
            $this->SendmailToUserByNewUpdateClassNotification($classId, $updateInformationClass);
        }
    }

    protected function saveCourseVenueAddress($courseId) {
        $venuesWithCourse = CourseWithVenue::model()->findByAttributes(array('courses_id' => $courseId));
        $BeforeUpdatecourseWithVenue = '';
        $BeforeUpdatecourseBatch = '';
        $BeforeUpdatecourseVenueBatch = '';
        if (!empty($venuesWithCourse)) {
            $updateInformationCourse[] = 'Course';
            /* getting information regarding course for mail */
            $AllvenueId = courses::getCourseWithVenues($courseId);
            foreach ($AllvenueId as $value) {
                $BeforeUpdatecourseWithVenue[] = $value['course_venue_id'];
                $BeforeUpdatecourseBatch = courses::getCoursesBatch($courseId, $value['course_venue_id']);
                foreach ($BeforeUpdatecourseBatch as $key => $value) {
                    $BeforeUpdateBatchDateFrom[] = $value['date_from'];
                    $BeforeUpdateBatchDateTo[] = $value['date_to'];
                    $BeforeUpdateBatchPrice[] = $value['price'];
                    $BeforeUpdateBatchSeats[] = $value['seats'];
                }
            }
            $this->deleteclassCourseDetails($courseId);
        }

        /*         * ************ save venue **************** */
        if (isset($_POST['ClassVenue']['name'])) {
            for ($venukey = 0; $venukey < count($_POST['ClassVenue']['name']); $venukey++) {
                /*                 * ************ save class with venue **************** */
                $venueIndex = $_POST['venueIndex'][$venukey];
                if (isset($_POST['ClassVenue']['venueId'][$venukey]) && !empty($_POST['ClassVenue']['venueId'][$venukey])) {
                    /* Here if user select venue from drop down list */
                    $courseWithVenue = new CourseWithVenue;
                    $courseWithVenue->setAttribute('courses_id', $courseId);
                    $courseWithVenue->setAttribute('course_venue_id', $_POST['ClassVenue']['venueId'][$venukey]);
                    $courseWithVenue->save(false);
                    $venueId = $_POST['ClassVenue']['venueId'][$venukey];
                } else {
                    $modelClassVenue = new ClassVenue;
                    $modelClassVenue->setAttribute('name', $_POST['ClassVenue']['name'][$venukey]);
                    $modelClassVenue->setAttribute('address_line1', $_POST['ClassVenue']['address_line1'][$venukey]);
                    $modelClassVenue->setAttribute('address_line2', $_POST['ClassVenue']['address_line2'][$venukey]);
                    $modelClassVenue->setAttribute('venue_locality', $_POST['ClassVenue']['venue_locality'][$venukey]);
                    $modelClassVenue->setAttribute('zip_code', $_POST['ClassVenue']['zip_code'][$venukey]);
                    $modelClassVenue->setAttribute('country_id', $_POST['ClassVenue']['country_id'][$venukey]);
                    $modelClassVenue->setAttribute('state_id', $_POST['ClassVenue']['state_id'][$venukey]);
                    $modelClassVenue->setAttribute('city_id', $_POST['ClassVenue']['city_id'][$venukey]);
                    $modelClassVenue->setAttribute('users_id', getLoginUserId());
                    $modelClassVenue->setAttribute('status', SkillConfig::STATUS_ACTIVE);
                    $modelClassVenue->setAttribute('create_time', SkillConfig::CreateDateTime());
                    $modelClassVenue->save(false);
                    ClassWithVenue::saveLocality($_POST['ClassVenue']['venue_locality'][$venukey]);
                    $courseWithVenue = new CourseWithVenue;
                    $courseWithVenue->setAttribute('courses_id', $courseId);
                    $courseWithVenue->setAttribute('course_venue_id', $modelClassVenue->id);
                    $courseWithVenue->save(false);
                    $venueId = $modelClassVenue->id;
                }
                if (!empty($venuesWithCourse)) {
                    if (!in_array($venueId, $BeforeUpdatecourseWithVenue)) {
                        $updateInformationCourse[] = "Venue";
                    }
                }

                /*                 * ************ save batches according to venue **************** */

                if (isset($_POST['batchIndex'][$venueIndex])) {
                    for ($batchKey = 0; $batchKey < count($_POST['batchIndex'][$venueIndex]); $batchKey++) {
                        if (isset($_POST['CourseBatche']['ClassVenue'][$venueIndex]['seats'][$batchKey])) {
                            $modelCourseBatche = new CourseBatche;
                            $modelCourseBatche->setAttribute('date_from', $_POST['CourseBatche']['ClassVenue'][$venueIndex]['date_from'][$batchKey]);
                            $modelCourseBatche->setAttribute('date_to', $_POST['CourseBatche']['ClassVenue'][$venueIndex]['date_to'][$batchKey]);
                            $modelCourseBatche->setAttribute('price', $_POST['CourseBatche']['ClassVenue'][$venueIndex]['price'][$batchKey]);
                            $modelCourseBatche->setAttribute('seats', $_POST['CourseBatche']['ClassVenue'][$venueIndex]['seats'][$batchKey]);
                            $modelCourseBatche->setAttribute('courses_id', $courseId);
                            $modelCourseBatche->setAttribute('course_venue_id', $venueId);
                            $modelCourseBatche->save(false);
                            $batchIndex = $_POST['batchIndex'][$venueIndex][$batchKey];
                            if (!empty($venuesWithCourse)) {
                                if ((!in_array($_POST['CourseBatche']['ClassVenue'][$venueIndex]['date_from'][$batchKey], $BeforeUpdateBatchDateFrom)) || (!in_array($_POST['CourseBatche']['ClassVenue'][$venueIndex]['date_to'][$batchKey], $BeforeUpdateBatchDateTo)) || (!in_array($_POST['CourseBatche']['ClassVenue'][$venueIndex]['price'][$batchKey], $BeforeUpdateBatchPrice)) || (!in_array($_POST['CourseBatche']['ClassVenue'][$venueIndex]['seats'][$batchKey], $BeforeUpdateBatchSeats))) {
                                    $updateInformationCourse[] = "Batch";
                                      Courses::model()->updateByPk($courseId, array('course_exp' => SkillConfig::STATUS_DEACTIVE));
                                }
                            }
                            /*                             * ************ save batches early discount **************** */
                            if (isset($_POST['ClassEarlyDiscount']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['valid_to'])) {
                                for ($k = 0; $k < count($_POST['ClassEarlyDiscount']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['valid_to']); $k++) {
                                    if ($_POST['ClassEarlyDiscount']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['valid_to'][$k] <> ""):
                                        $modelCourseEarlyDiscount = new CourseEarlyDiscount;
                                        $modelCourseEarlyDiscount->setAttribute('discount_price', $_POST['ClassEarlyDiscount']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['discount_price'][$k]);
                                        $modelCourseEarlyDiscount->setAttribute('in_percentage', $_POST['ClassEarlyDiscount']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['in_percentage'][$k]);
                                        $modelCourseEarlyDiscount->setAttribute('valid_to', $_POST['ClassEarlyDiscount']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['valid_to'][$k]);
                                        $modelCourseEarlyDiscount->setAttribute('status', SkillConfig::STATUS_ACTIVE);
                                        $modelCourseEarlyDiscount->setAttribute('course_batche_id', $modelCourseBatche->id);
                                        $modelCourseEarlyDiscount->setAttribute('courses_id', $courseId);
                                        $modelCourseEarlyDiscount->save(false);
                                    endif;
                                }
                            }

                            /*                             * ************ save batches group discount **************** */
                            if (isset($_POST['GroupDiscount']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['group_size'])) {
                                for ($k = 0; $k < count($_POST['GroupDiscount']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['group_size']); $k++) {
                                    if ($_POST['GroupDiscount']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['group_size'][$k] <> ""):
                                        $modelCourseGroupDiscount = new CourseGroupDiscount;
                                        $modelCourseGroupDiscount->setAttribute('discount_amount', $_POST['GroupDiscount']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['discount_amount'][$k]);
                                        $modelCourseGroupDiscount->setAttribute('discount_in_percentage', $_POST['GroupDiscount']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['discount_in_percentage'][$k]);
                                        $modelCourseGroupDiscount->setAttribute('group_size', $_POST['GroupDiscount']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['group_size'][$k]);
                                        $modelCourseGroupDiscount->setAttribute('course_batche_id', $modelCourseBatche->id);
                                        $modelCourseGroupDiscount->setAttribute('courses_id', $courseId);
                                        $modelCourseGroupDiscount->save(false);
                                    endif;
                                }
                            }


                            /*                             * ************ save batches structure **************** */
                            if (isset($_POST['ClassStructures']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['start_time'])) {
                                for ($k = 0; $k < count($_POST['ClassStructures']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['start_time']); $k++) {
                                    if ($_POST['ClassStructures']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['start_time'][$k] <> "" && $_POST['ClassStructures']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['end_time'][$k] <> "" && $_POST['ClassStructures']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['description'][$k] <> ""):
                                        $modelClassStructure = new ClassStructures;
                                        $modelClassStructure->setAttribute('start_time', $_POST['ClassStructures']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['start_time'][$k]);
                                        $modelClassStructure->setAttribute('end_time', $_POST['ClassStructures']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['end_time'][$k]);
                                        $modelClassStructure->setAttribute('description', $_POST['ClassStructures']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['description'][$k]);
                                        $modelClassStructure->setAttribute('course_batche_id', $modelCourseBatche->id);
                                        $modelClassStructure->setAttribute('courses_id', $courseId);
                                        $modelClassStructure->save(FALSE);
                                    endif;
                                }
                            }


                            if (isset($_POST['CourseBatche']['ClassVenue'][$venueIndex]['no_of_session'][$batchKey]) && $_POST['CourseBatche']['ClassVenue'][$venueIndex]['no_of_session'][$batchKey] > 0) {
                                /*                                 * ************ save batches date Session **************** */
                                if (isset($_POST['CourseBatcheDateSession']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['date'])) {
                                    for ($k = 0; $k < count($_POST['CourseBatcheDateSession']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['date']); $k++) {
                                        if ($_POST['CourseBatcheDateSession']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['date'][$k] <> "") {
                                            $modelCourseBatcheDateSession = new CourseBatcheDateSession;
                                            $modelCourseBatcheDateSession->setAttribute('date', $_POST['CourseBatcheDateSession']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['date'][$k]);
                                            $modelCourseBatcheDateSession->setAttribute('time_from', $_POST['CourseBatcheDateSession']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['time_from'][$k]);
                                            $modelCourseBatcheDateSession->setAttribute('time_to', $_POST['CourseBatcheDateSession']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['time_to'][$k]);
                                            if (isset($_POST['CourseBatcheDateSession']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['is_flexiblevalue'][$k]) && $_POST['CourseBatcheDateSession']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['is_flexiblevalue'][$k] == 1) {
                                                $modelCourseBatcheDateSession->setAttribute('is_flexible', 1);
                                            }
                                            $modelCourseBatcheDateSession->setAttribute('course_batche_id', $modelCourseBatche->id);
                                            $modelCourseBatcheDateSession->setAttribute('courses_id', $courseId);
                                            $modelCourseBatcheDateSession->save(false);
                                        }
                                    }
                                }
                            } else {
                                /*                                 * ************ save batches day Session **************** */
                                if (isset($_POST['CourseBatcheDaySession']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['schedule_id'])) {
                                    for ($k = 0; $k < count($_POST['CourseBatcheDaySession']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['schedule_id']); $k++) {
                                        $modelCourseBatcheDaySession = new CourseBatcheDaySession;
                                        $modelCourseBatcheDaySession->setAttribute('schedule_id', $_POST['CourseBatcheDaySession']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['schedule_id'][$k]);
                                        $modelCourseBatcheDaySession->setAttribute('time_from', $_POST['CourseBatcheDaySession']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['time_from'][$k]);
                                        $modelCourseBatcheDaySession->setAttribute('time_to', $_POST['CourseBatcheDaySession']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['time_to'][$k]);
                                        if (isset($_POST['CourseBatcheDaySession']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['is_flexiblevalue'][$k]) && $_POST['CourseBatcheDaySession']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['is_flexiblevalue'][$k] == 1) {
                                            $modelCourseBatcheDaySession->setAttribute('is_flexible', $_POST['CourseBatcheDaySession']['CourseBatche'][$batchIndex]['ClassVenue'][$venueIndex]['is_flexiblevalue'][$k]);
                                        }
                                        $modelCourseBatcheDaySession->setAttribute('course_batche_id', $modelCourseBatche->id);
                                        $modelCourseBatcheDaySession->setAttribute('courses_id', $courseId);
                                        $modelCourseBatcheDaySession->save(false);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if (!empty($venuesWithCourse)) {
            $this->SendmailToUserByNewUpdatecourseNotification($courseId, $updateInformationCourse);
        }
    }

    private static function saveCourseTicketBooked($courseId) {
        Courses::deleteClassTicketBooked($courseId);
        $modelTicketBooked = new TicketBooked;
        if (isset($_POST['TicketBooked'])) {
            $modelTicketBooked->setAttribute('no_of_days', $_POST['TicketBooked']['no_of_days']);
            $modelTicketBooked->setAttribute('no_of_hours', $_POST['TicketBooked']['no_of_hours']);
            $modelTicketBooked->setAttribute('courses_id', $courseId);
            $modelTicketBooked->setAttribute('action', $_POST['TicketBooked']['action']);
            $modelTicketBooked->save(FALSE);
        }
    }

    private static function saveCourseOtherInfo($courseId) {
        $model = Courses::model()->findByPk($courseId);
        if (isset($_POST['Courses']['course_other_information'])) {
            $model->setAttribute('course_other_information', $_POST['Courses']['course_other_information']);
            $model->save();
        }
    }

    private static function saveClassTicketBooked($classId) {
        Classes::deleteClassTicketBooked($classId);
        $modelTicketBooked = new TicketBooked;
        if (isset($_POST['TicketBooked'])) {
            $modelTicketBooked->setAttribute('no_of_days', $_POST['TicketBooked']['no_of_days']);
            $modelTicketBooked->setAttribute('no_of_hours', $_POST['TicketBooked']['no_of_hours']);
            $modelTicketBooked->setAttribute('classes_id', $classId);
            $modelTicketBooked->setAttribute('action', $_POST['TicketBooked']['action']);
            $modelTicketBooked->save(FALSE);
        }
    }

    private static function saveOtherInfo($classId) {
        $model = Classes::model()->findByPk($classId);
        if (isset($_POST['Classes']['class_other_information'])) {
            $model->setAttribute('class_other_information', $_POST['Classes']['class_other_information']);
            $model->save();
        }
    }

    public function actiongetAllVenue() {
        $model = new ClassVenue;
        $data = getVenueByUser($model);
        echo CHtml::tag('option', array('value' => ''), CHtml::encode('Select Venue Name'), true);
        foreach ($data as $value => $name) {
            echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
        }
    }

    public function actiongetAllCountry() {
        $data = Country::model()->findAllByAttributes(array('is_active' => SkillConfig::STATUS_ACTIVE, 'id' => SkillConfig::ACTIVE_COUNTRY));
        $data = CHtml::listData($data, 'id', 'name');
        echo CHtml::tag('option', array('value' => ''), CHtml::encode('Select Country Name'), true);
        foreach ($data as $value => $name) {
            echo CHtml::tag('option', array('value' => $value, 'selected' => ($value == SkillConfig::ACTIVE_COUNTRY) ? 'selected' : ''), CHtml::encode($name), true);
        }
    }

    public function actiondynamicState() {
        $data = State::model()->findAll('country_id=:country_id AND is_active=:is_active AND id=:id', array(':country_id' => (int) $_POST['countryId'], ':is_active' => SkillConfig::STATUS_ACTIVE, ':id' => SkillConfig::ACTIVE_STATE));
        $data = CHtml::listData($data, 'id', 'name');
        foreach ($data as $value => $name) {
            echo CHtml::tag('option', array('value' => $value, 'selected' => ($value == SkillConfig::ACTIVE_STATE) ? 'selected' : ''), CHtml::encode($name), true);
        }
    }

    public function actiondynamicCity() {
        $data = City::model()->findAll('state_id=:state_id AND status=:status', array(':state_id' => (int) $_POST['stateId'], 'status' => SkillConfig::STATUS_ACTIVE));
        $data = CHtml::listData($data, 'id', 'city_name');
        foreach ($data as $value => $name) {
            echo CHtml::tag('option', array('value' => $value, 'selected' => ($value == SkillConfig::ACTIVE_CITY) ? 'selected' : ''), CHtml::encode($name), true);
        }
    }

    public function actionSelectedVenue() {
        /* Note user_id=1 staticly for use when select venue login user otherwise when select venue without login user */
        $data = ClassVenue::model()->find('id=:id AND status=:status', array(':id' => (int) $_POST['venueId'], 'status' => SkillConfig::STATUS_ACTIVE));
        echo ($_POST['user_id'] == '1') ? CJSON::encode($data) : '<p id="p1venue">' . $data->name . '</p> <p id="p2venue">' . $data->address_line1 . ' ' . $data->address_line2 . '</p> <p id="p3venue">' . $data->city->city_name . ' ' . $data->state->name . '</p> <p id="p4venue">' . $data->country->name . ' ' . $data->zip_code . '</p>';
    }

    private function deleteclassCourseDetails($courseId) {
        Courses::deleteCoursesBatcheEarlyDiscount($courseId);
        Courses::deleteCoursesBatcheGroupDiscount($courseId);
        Courses::deleteCoursesBatcheDaySessions($courseId);
        Courses::deleteCoursesBatcheDateSessions($courseId);
        Courses::deleteCoursesWithVenue($courseId);
        Courses::deleteCoursesBatches($courseId);
        Courses::deleteCoursesStructure($courseId);
    }

    //this function user mail class update notification ..
    private function SendmailToUserByNewUpdateClassNotification($classId, $updateInformationClass) {
        /* This is for make query users */
        $updateInfo = '';
        $classDeatls = Classes::model()->findByPk($classId);
        $userNames = Users::getFrontEndUser($classDeatls->users_id);
        $trainnername = $userNames->first_name . '  ' . $userNames->last_name;
        $queryuser = MakeQuery::model()->findAllByAttributes(array('classes_id' => $classId));
        $updateInformationClass = array_unique($updateInformationClass);
        foreach ($updateInformationClass as $key => $value) {
            $updateInfo.='<li>' . $updateInformationClass[$key] . '</lI>';
        }
        $updateInfo = '<ul>' . $updateInfo . '</ul>';
        $template = Message::UPDATECLASS_TEMPLATE_NOTIFICATION;
        $mailmodel = EmailTemplate::model()->findByPk($template);
        $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');
        $mailtemp = Template::model()->findByPk($mailmodel->template_id);        
        $classlink = '<a href="http://' . $_SERVER['HTTP_HOST'] . $this->createUrl('workshop-'.$classDeatls->id.'/'.$classDeatls->class_seo_title). '" class="linkclass" target="_blank">View ' . SkillConfig::CLASS_WORK_SHOP . '</a>';
        $classCourseName = $classDeatls->class_titile;
        if (count($queryuser) > 0) {
            foreach ($queryuser as $allSubscriberUser) {
                $mailto = $allSubscriberUser->email;
                $userName = $allSubscriberUser->name;
                $arrayFind = array('[username]', '[trainer_name]', '[updateclass]', '[classcoursename]', '[classCourseViewdetailsLink]');
                $arrayReplace = array($userName, $trainnername, $updateInfo, $classCourseName, $classlink);
                $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
                $subject = $mailmodel->subject;
                $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
                try {
                    SkillSendMail::SendMail($mailto, $subject, $body);
                } catch (Exception $e) {
                    echo $e;
                    exit;
                }
            }
        }
    }

    private function SendmailToUserByNewUpdatecourseNotification($courseId, $updateInformationClass) {
        /* This is for make query users */
        $updateInfo = '';
        $courseDeatls = Courses::model()->findByPk($courseId);
        $userNames = Users::getFrontEndUser($courseDeatls->users_id);
        $trainnername = $userNames->first_name . '  ' . $userNames->last_name;
        $queryuser = MakeQuery::model()->findAllByAttributes(array('courses_id' => $courseId));
        $updateInformationClass = array_unique($updateInformationClass);
        foreach ($updateInformationClass as $key => $value) {
            $updateInfo.='<li>' . $updateInformationClass[$key] . '</lI>';
        }
        $updateInfo = '<ul>' . $updateInfo . '</ul>';
        $template = Message::UPDATECOURSE_TEMPLATE_NOTIFICATION;
        $mailmodel = EmailTemplate::model()->findByPk($template);
        $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');
        $mailtemp = Template::model()->findByPk($mailmodel->template_id);
        $courselink = '<a href="http://' . $_SERVER['HTTP_HOST'] . $this->createUrl('courses-'.$courseDeatls->id.'/'.$courseDeatls->course_seo_title) . '" class="linkclass" target="_blank">View ' . SkillConfig::Course_WORK_SHOP . '</a>';
        $classCourseName = $courseDeatls->course_titile;
        if (count($queryuser) > 0) {
            foreach ($queryuser as $allSubscriberUser) {
                $mailto = $allSubscriberUser->email;
                $userName = $allSubscriberUser->name;
                $arrayFind = array('[username]', '[trainer_name]', '[updatecourse]', '[classcoursename]', '[classCourseViewdetailsLink]');
                $arrayReplace = array($userName, $trainnername, $updateInfo, $classCourseName, $courselink);

                $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
                $subject = $mailmodel->subject;
                $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
                try {
                    SkillSendMail::SendMail($mailto, $subject, $body);
                } catch (Exception $e) {
                    echo $e;
                    exit;
                }
            }
        }
    }

    public function actiongetLocality() {
        $Locality = array();
        $data = Yii::app()->db->createCommand()
                ->select('*')
                ->from('skill_locality_name')
                ->where('locality_name LIKE  "%' . $_POST['locality_name'] . '%"')
                ->order('locality_name ASC')
                ->queryAll();
        foreach ($data as $value) {
            $Locality[] = trim($value['locality_name']);
        }
        if (!empty($Locality)) {
            echo CJSON::encode($Locality);
        } else {
            echo SkillConfig::STATUS_DEACTIVE;
        }
    }

    public function actiongetBatchDetails() {
        $this->layout = FALSE;
        if (isset($_POST['venueId'])) {
            $model = getClaCourseInfo('Classes', $_POST['classId']);
            $venueArrayVal = $_POST['venueId'];
            echo $this->renderPartial('//classBatch/_getVenueBatchDetails', array('venueArrayVal' => $venueArrayVal, 'model' => $model));
            Yii::app()->end();
        }
    }

    public function actiongetcourseBatchDetails() {
        $this->layout = FALSE;
        if (isset($_POST['venueId'])) {
            $model = getClaCourseInfo('Courses', $_POST['courseId']);
            $venueArrayVal = $_POST['venueId'];
            echo $this->renderPartial('//courseBatche/_getVenuecourseBatchDetails', array('venueArrayVal' => $venueArrayVal, 'model' => $model));
            Yii::app()->end();
        }
    }

}
